import React, { Component } from 'react';
import { Button, Form, Input, Checkbox, Switch, Spin } from 'antd'
import { messages } from "share/common";
import {connect} from 'react-redux';
import Priority from 'components/template/priority';
const FormItem = Form.Item;
const Group = Checkbox.Group;
import 'styles/supplier-management/new-consumer-management/edit-frams/edit-frame.scss'
import NewConsumerServer from '../new-consumer-server'
import {message} from "antd/lib/index";
import ConsumerUtil from '../consumer-util';

@Form.create()
class HeliosHotelFrame extends Component{

  constructor(props){
    super(props);
    this.isLock = false;
    this.options = [
      { label: messages('supplier-1.key81')/*酒店*/, value: 'HOTEL' },
    ];
    this.keyName = ['openType','openPC','openPCOrder','openApproval'];
    this.state = {
      editData: {},
      loading: false,
      isNew: false,
      priDefalultValue: {},
    }
  }

  componentWillMount(){
    const {params, tenant} = this.props;
    const initValue = ConsumerUtil.initPriorityData(this.props);
    if(params.companyInfos){
      initValue.distribution = {
        companies: params.companyInfos ? params.companyInfos : []
      }
    }
    this.setState({
      editData: params,
      isNew: params.levelCode ? false : true,
      priDefalultValue: initValue
    }, this.props.form.resetFields);
  }

  onPriorityChange = (values) => {
    this.setState({
      priDefalultValue: values,
    })
  }

  onCancelEdit = () => {
    this.props.close();
    this.props.form.resetFields();
  };

  onSubmitEdit = () => {
    if(this.isLock){
      return;
    }
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err){
        const {priDefalultValue, isNew, editData} = this.state;
        const authData = JSON.parse(JSON.stringify(priDefalultValue));
        const {tenant} = this.props;
        if (!authData) {
          message.error(messages('supplier-1.key185')/*请填写所属组织*/);
          return;
        }
        if(!authData.distribution && authData.levelCode != 'COMPANY'){
          message.error(messages('supplier-1.key186')/*启用公司不支持通用*/);
          return;
        }
        if(authData.levelCode != 'COMPANY' && authData.distribution.companies.length <= 0){
          message.error(messages('supplier-1.key187')/*请填写公司*/);
          return;
        }
        const companies = {companies:{}};
        if(authData.distribution){
          authData.distribution.companies.forEach(item => {
            companies.companies[item.companyOID] = item.name;
          })
          delete authData.distribution;
        }
        let upParams = Object.assign({},values,authData,companies);
        this.keyName.forEach(item => {
          upParams[item] = upParams[item].join('|');
        });
        upParams.corpStatus = upParams.enabled ? 'NORMAL' : 'INVALID';
        upParams.tenantId = tenant.id;
        upParams.tenantName = tenant.tenantName;
        if(!isNew){
          upParams = Object.assign({id: editData.id}, upParams);
        }
        // console.log(upParams);
        this.isLock = true;
        NewConsumerServer(this).submitEditData(upParams).then(res => {
          this.isLock = false;
          if(!res.data.passFlag && res.data.message){
            message.error(res.data.message);
          }else{
            this.props.close(true);
          }
        });
      }
    })
  };

  isOpenServer = (value) => {
    if(!value){
     // todo
    }
  }

  render(){
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { editData, loading, isNew, priDefalultValue } = this.state;
    const formLayout = {
      labelCol: {span: 6, offset: 1},
      wrapperCol: {span: 14}
    };
    return (
      <div className='edit-frame'>
        <Spin spinning={loading}>
          <Form className="new-form">
            <FormItem label={messages('supplier-1.key247')/*规则状态*/} {...formLayout}>
              {
                getFieldDecorator('enabled',{
                  initialValue:editData.enabled || false,
                  valuePropName:'checked',
                })(
                  <Switch onChange={this.isOpenServer} />
                )
              }
            </FormItem>
            <Priority
              top='TENANT'
              formItemLayout={formLayout}
              disabledTop={!isNew}
              companyProps={{disabled: !isNew, valueKey: 'companyOID'}}
              defaultValue={priDefalultValue}
              onChange={this.onPriorityChange}
            />
            <FormItem label={messages('supplier-1.key248')/*应用状态*/} {...formLayout}>
              {
                getFieldDecorator('enabled2',{
                  initialValue:editData.enabled || false,
                  valuePropName:'checked',
                })(
                  <Checkbox>{messages('supplier-1.key35')/*启用temp*/}</Checkbox>
                )
              }
            </FormItem>
            <h3 className='slide-title' style={{borderBottom: 0}}>
              <div className='other-rule-edit-title'>
                {messages('supplier-1.key196')/*申请单相关设置*/}
              </div>
            </h3>
            <FormItem className='form-label-style' label={messages('supplier-1.key197')/*行程上可选该服务商*/} {...formLayout}>
              {
                getFieldDecorator('openApproval',{
                  initialValue: editData.openApproval || [],
                })(<Group options={this.options}/>)
              }
            </FormItem>
            <FormItem className='form-label-style' label={messages('supplier-1.key249')/*行程上可选国际城市*/} {...formLayout}>
              {
                getFieldDecorator('openApprovalCity',{
                  initialValue: editData.openApprovalCity || false,
                  valuePropName: 'checked',
                })(
                  <Checkbox>{messages('supplier-1.key35')/*启用temp*/}</Checkbox>
                )
              }
            </FormItem>
            <h3 className='slide-title' style={{borderBottom: 0}}>
              <div className='other-rule-edit-title'>
                {messages('supplier-1.key198')/*PC端入口*/}
              </div>
            </h3>
            <FormItem className='form-label-style' label={messages('supplier-1.key199')/*服务商预订首页*/} {...formLayout}>
              {
                getFieldDecorator('openPC',{
                  initialValue: editData.openPC || [],
                })(<Group options={this.options}/>)
              }
            </FormItem>
            <FormItem className='form-label-style' label={messages('supplier-1.key200')/*服务商订单列表*/} {...formLayout}>
              {
                getFieldDecorator('openPCOrder',{
                  initialValue: editData.openPCOrder || [],
                })(<Group options={this.options}/>)
              }
            </FormItem>
          </Form>
        </Spin>
        <br/><br/><br/><br/>
        <div className='affix-bottom'>
          <Button type="primary" loading={loading}  onClick={this.onSubmitEdit}>
            {messages('common.ok')/*确定*/}
          </Button>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <Button onClick={this.onCancelEdit}>
            {messages('common.cancel')/*取消*/}
          </Button>
        </div>
      </div>
    )
  }
}


HeliosHotelFrame.getEditData = record => {
  const params = JSON.parse(JSON.stringify(record));
  let keyName = ['openType','openPC','openPCOrder','openApproval'];
  keyName.forEach(item => {
    if(params[item]) {
      params[item] = params[item].split('|');
    }
  });
  return params;
};

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
  }
}

export default connect(mapStateToProps)(HeliosHotelFrame);
